$(function () {
    $.get(baseURL + "basics/bwarehouse/getIsCheck/"+parseInt(localStorage.getItem("house")),function(r) {
        $("#jqGrid").jqGrid({
            url: baseURL + 'goods/bgoods/list',
            datatype: "json",
            colModel: [
                {label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden: true},
                {label: '货物名称', name: 'goodsName', index: 'goods_name', width: 80, align: "center"},
                {
                    label: '货物所属货位',
                    name: 'allocation',
                    index: 'allocation_id',
                    width: 180,
                    align: "center",
                    formatter: function (value, options, row) {
                        return row.areaName + '' + row.shelveName + '' + row.allocationName;
                    }
                },
                {label: '货物单位', name: 'unitName', index: 'unit_id', width: 80, align: "center"},
                {label: '所属种类', name: 'goodsTypeName', index: 'goods_type_id', width: 80, align: "center"},
                {label: '编码', name: 'labelErp', index: 'label_erp', width: 160, align: "center"},
                {label: '条形码', name: 'barCode', index: 'bar_code', width: 80, hidden: true},
                {label: '货物图片', name: 'goodsPic', index: 'goods_pic', width: 80, hidden: true},
                {label: '下次检验时间', name: 'dueDate', index: 'due_date', width: 80, hidden: !r.isCheck, align: "center"},
                {label: '货物生产厂家', name: 'goodsFactory', index: 'goods_factory', width: 100, align: "center"},
                {label: '货物型号', name: 'goodsModel', index: 'goods_model', width: 60, align: "center"},
                {label: '货物规格', name: 'goodsSpecs', index: 'goods_specs', width: 60, align: "center"},
                {label: '货物详情', name: 'goodsDetail', index: 'goods_detail', width: 80, hidden: true},
                {label: '备注', name: 'remark', index: 'remark', width: 80, hidden: true},
                {label: '创建人', name: 'createUserId', index: 'create_user_id', width: 80, hidden: true},

                {
                    label: '创建时间',
                    name: 'createTime',
                    index: 'create_time',
                    width: 80,
                    align: "center",
                    formatter: function (value, options, row) {
                        return new Date(value).Format('yyyy-MM-dd HH:mm:ss');
                    }
                },
                {
                    label: '修改时间',
                    name: 'updateTime',
                    index: 'update_time',
                    width: 60,
                    hidden: true,
                    align: "center",
                    formatter: function (value, options, row) {
                        return new Date(value).Format('yyyy-MM-dd HH:mm:ss');
                    }
                },
                {
                    label: '上架状态',
                    name: 'isUpshelf',
                    index: 'is_upshelf',
                    width: 40,
                    align: "center",
                    formatter: function (value, options, row) {
                        return value === 1 ?
                            '<span class="label label-success" value="1">上架</span>' :
                            '<span class="label label-danger" value="0">未上架</span>';
                    }
                },
                {
                    label: '货物状态',
                    name: 'goodsStatusName',
                    index: 'goods_status_name',
                    width: 40,
                    align: "center",
                    /*formatter: function (grade, index, row) {
                        if (grade == 0) {
                            grade = "正常";
                        } else if (grade == 1) {
                            grade = "借出";
                        } else if (grade == 2) {
                            grade = "被预约";
                        }else if (grade == 3) {
                            grade = "待检测";
                        }
                        return grade;
                    }*/
                },
                {
                    label: '启用状态',
                    name: 'isUsed',
                    index: 'is_used',
                    width: 40,
                    align: "center",
                    formatter: function (value, options, row) {
                        return value === 1 ?
                            '<span class="label label-success" value="1">启用</span>' :
                            '<span class="label label-danger" value="0">未启用</span>';
                    }
                },
                {
                    label: '货物是否上架，1上架，0未上架',
                    name: 'isUpshelf',
                    index: 'is_upshelf',
                    width: 80,
                    align: "center",
                    hidden: true
                },
                {
                    label: '货物状态,0正常，1借出，2预约',
                    name: 'goodsStatus',
                    index: 'goods_status',
                    width: 80,
                    align: "center",
                    hidden: true
                },
                {label: '是否启用,0未启用，1启用', name: 'isUsed', index: 'is_used', width: 80, align: "center", hidden: true},
                {label: '是否删除，1删除，0未删除', name: 'isDel', index: 'is_del', width: 80, hidden: true}
            ],
            viewrecords: true,
            height: 385,
            rowNum: 10,
            rowList: [10, 30, 50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth: true,
            multiselect: true,
            pager: "#jqGridPager",
            jsonReader: {
                root: "goodsList.list",
                page: "goodsList.pageNum",
                total: "goodsList.pages",
                records: "goodsList.total"
            },
            prmNames: {
                page: "page",
                rows: "limit",
                order: "order"
            },
            postData: {
                wareHouseId: parseInt(localStorage.getItem("house"))
            },
            gridComplete: function () {
                //隐藏grid底部滚动条
                $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            }
        });
    });
});

var vm = new Vue({
	el:'#rrapp',
	data :function(){
		var validateAllocation = function(rule, value, callback){
			if (value === ''||value===undefined) {
				callback(new Error('请选择物品所属货位'));
			} else {
				if (value.length!=3) {
					// 对第二个密码框单独验证
					callback(new Error('所属货位选择不对，请重新选择！！'));
				}
				callback();
			}
		};
		return {
			showList: true,
			title: null,
			bGoods: {
			},
			bGoodsList:[],//上架数组
			goodsPic:'',
			goodsAreaList: [],//查询条件的所属货位
			unitList:[],//货物单位
			typeList:[],//类型,
            testList:[
            	{id:0,name:'完好'},{id:1,name:'损坏'},
            	],
			search: {
				goodsName: '',
				allocationId: '',

				wareHouseId: parseInt(localStorage.getItem("house"))
			},
            bGoodsTest:{
				type:0
			},
			isShow: false,//是否只读
			ruleValidate: {//验证
				goodsName: [{required: true, trigger: 'blur', message: '请输入物品名称！'}],
				allocation: [{required: true,type:'array',validator: validateAllocation, trigger: 'blur'}],
				/*unitId: [{required: true,trigger: 'blur',type:'number', message: '请选择货物单位！'}],*/
				/*goodsTypeId: [{required: true,trigger: 'blur',type:'number', message: '请选择所属种类！'}],*/
			},
			showShlef:false,//是否显示上架类列表
			isUpshelf: false,//是否上架 默认false
			isTest: false,//检测页面是否显示 默认false
            isCheck:false,
			uploadUrl:baseURL+'/sys/oss/upload/',
			columns:[
				{
					title: '货物名称',
					key: 'goodsName',

					align:'center',
				},
				{
					title: '货物所属货位',
					key: 'allocation',

					align:'center',
				},
				{
					title: '货物对应编码',
					key: 'labelErp',
					align:'center',
				},
				{
					title: '操作',
					key: 'action',
					width: 200,

					render: function(h, params) {
						return h('div', [
							h('Button', {
								props: {
									type: 'primary',
									size: 'small'
								},
								style: {
									marginRight: '5px'
								},
								on: {
									click:function(){
										//this.clearLabEcp(params.index)
                                        vm.bGoodsList[params.index].labelErp=''
									}
								}
							}, '清除')
						]);
					}
				}
			],
			epcList:[],
			epcMap:{},
		}
	},
	created:function(){
			this.getAllocationList();
			this.getUnitList();
			this.getGoodsTypeList();
			this.getIsCheck();
	},
	methods: {
        getIsCheck:function(){
            $.get(baseURL + "basics/bwarehouse/getIsCheck/"+parseInt(localStorage.getItem("house")),function(r){
                vm.isCheck = r.isCheck;
            });
		},
		reback:function(){//返回
			vm.showShlef=false;
            vm.closeWebsocket();
		},
		selectChange:function(selVal){
			this.$forceUpdate()
		},
        detail:function(event){
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            vm.showList = false;
            vm.showAdd = false;
            vm.title = "详情";

            vm.getInfo(id);

        },
		reset:function(event){
			vm.search={
				goodsName:'',
				allocationId:''
			}
			this.reload(event);
		},
		getGoodsTypeList:function(){
			$.post(baseURL + "basics/bgoodstype/list",function(r){
				vm.typeList = r.goodsTypeList.list;
			});
		},
		getUnitList:function(){
			$.post(baseURL + "basics/bgoodsunit/list",function(r){
				vm.unitList = r.goodsUnitList.list;
			});
		},
		getAllocationList:function(){
			$.post(baseURL + "basics/bgoodsarea/getTreeList", {'wareHouseId':parseInt(localStorage.getItem("house"))},function(r){
				vm.goodsAreaList = r.list;
			});
		},
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.bGoods = {};
			vm.isShow=false;//可读
			vm.bGoods.isUpshelf=0;
			vm.goodsPic='';
			this.$refs['bGoods'].resetFields();

		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			if(id){

			}
			//vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (name) {
			/*this.$Spin.show({
				render: function h() {
					return h('div', [
						h('Icon', {
							'class': 'demo-spin-icon-load',
							props: {
								type: 'ios-loading',
								size: 18
							}
						}),
						h('div', 'Loading')
					])
				}
			});*/
			this.$refs[name].validate(function(valid){
				console.log(valid)
				if(valid) {
					vm.bGoods.goodsPic =vm.goodsPic;
					var url = vm.bGoods.id == null ? "goods/bgoods/save" : "goods/bgoods/update";
					vm.bGoods.allocationId=vm.bGoods.allocation[vm.bGoods.allocation.length-1];
					vm.bGoods.wareHouseId=vm.search.wareHouseId;
					var param = {
						"goods": vm.bGoods
					};

					$.ajax({
						type: "POST",
						url: baseURL + url,
						contentType: "application/json",
						data: JSON.stringify(param),
						success: function (r) {
							//vm.$Spin.hide();
							if (r.code === 0) {
								alert('操作成功', function (index) {
									vm.reload();
								});
							} else {
								alert(r.msg);
							}
						}
					});
				}else{
					//vm.$Spin.hide();
				}
			})
		},
		//下架
		unUpShlef:function(){
			var  list=[];
			var ids = getSelectedRows();
			for (var i = 0; i < ids.length; i++) {
				var row=getRowData(ids[i]);
				var obj={
					id: row.id,
					goodsName:row.goodsName,
					allocation:row.allocation,
					labelErp:row.labelErp,
					isUpshelf:0
				}
				if(row.isUpshelf==0){
					alert("请选择已上架物品！！")
					return;
				}
				if(row.goodsStatus!=0){
					alert("请选择状态为正常的物品！！")
					return;
				}
				list.push(obj)
			}
			confirm('确定要下架选中的物品？', function(){
				$.ajax({
					type: "POST",
					url: baseURL + "goods/bgoods/updateUpShelfBatch",
					contentType: "application/json",
					data:  JSON.stringify(list),
					success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								vm.reload()
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});

		},
		//上架
		showShlefList:function(event){
			vm.bGoodsList=[];
			var ids = getSelectedRows();
			for (var i = 0; i < ids.length; i++) {
				var row=getRowData(ids[i]);
				var obj={
					id: row.id,
					goodsName:row.goodsName,
					allocation:row.allocation,
					labelErp:row.labelErp,
					isUpshelf:1
				}
				if(row.isUpshelf==1){
					alert("请选择未上架物品！！")
					return;
				}
				vm.bGoodsList.push(obj)
			}
			vm.showShlef=true;
			//vm.initWebsocket();
		},
		readLabelErp:function(ind){
			var obj=vm.bGoodsList[ind];
			/*$.post(baseURL + "goods/bgoods/readLabelErp",obj,function(r){
				vm.bGoodsList[index].labelErp = r.labelErp;
			});*/
			$.ajax({
				type: "POST",
				url: baseURL + "goods/bgoods/readLabelErp",
				contentType: "application/json",
				data: JSON.stringify(obj),
				success: function(r){
					if(r.code == 0){
						alert('操作成功', function(index){
							vm.bGoodsList[ind].labelErp = r.labelErp;
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		//上架提交
		submit:function(ind){
			var obj=vm.bGoodsList;
			for (var i = 0; i < obj.length ; i++) {
				if(obj[i].labelErp==''){
					alert('尚有商品未读取编码，请读取完成后再点击上架！！');
					return;
				}
			}
           /* if(vm.bGoodsList.length!=vm.epcList.length){
                alert('尚有商品未读取编码，请读取完成后再点击上架！！');
                return;
            }*/
			$.ajax({
				type: "POST",
				url: baseURL + "goods/bgoods/updateUpShelfBatch",
				contentType: "application/json",
				data: JSON.stringify(obj),
				success: function(r){
					if(r.code == 0){
						alert('操作成功', function(index){
							vm.showShlef=false;
							vm.reload();
                            vm.closeWebsocket();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},

		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
            for (var i = 0; i < ids.length; i++) {
                var row=getRowData(ids[i]);
                if(row.isUpshelf==1){
                    alert("删除的物品中存在上架物品，请去除后在进行该操作！！")
                    return;
                }
            }
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "goods/bgoods/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){

			$.get(baseURL + "goods/bgoods/info/"+id, function(r){
                vm.bGoods = r.map.goods;
                var allocation= r.map.goods.allocation;
                vm.bGoods.allocation=allocation.split(',')
				vm.goodsPic =r.map.goods.goodsPic;
                if(vm.title=='检测'){
                    if(vm.bGoods.goodsStatus!=3){
                        alert("只有处于待检测状态下的物品才能被检测！！");
                        vm.isTest=false;
                        return;
                    }
				}else{
                    if(vm.title=='详情'){
                        vm.isShow=true;
                    }else if(vm.bGoods.isUpshelf==0){
                        vm.isShow=false;
                        vm.showList = false;
                    }
                    if(vm.bGoods.isUpshelf==1){
                        alert("已上架物品不能修改！！")
                        return;
                    }
                }

            });
		},
		reload: function (event) {
			vm.showList = true;
			vm.isTest=false;
			var obj={}
            obj.wareHouseId=vm.search.wareHouseId;
            obj.goodsName=vm.search.goodsName;
            obj.goodsAreaId='';
            obj.goodsShelveId='';
            obj.allocationId='';
			if(vm.search.allocationId!=undefined&&vm.search.allocationId!=''&&vm.search.allocationId.length>0){

				for (var i=0;i<vm.search.allocationId.length;i++){
					if(i==0){
						obj.goodsAreaId=vm.search.allocationId[0]
					}else if(i==1){
                        obj.goodsShelveId=vm.search.allocationId[1]
					}else{
                        obj.allocationId=vm.search.allocationId[2]
					}
				}
			}

			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:obj
            }).trigger("reloadGrid");
		},
		changeisUpshelf:function(){
			vm.bGoods.isUpshelf=vm.isUpshelf?1:0;
		},
		handleAvatarSuccess:function(res, file) {
			vm.goodsPic = res.url;
		},
		beforeAvatarUpload:function(file) {
			var isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
			var isLt2M = file.size / 1024 / 1024 < 2;

			if (!isJPG) {
				this.$message.error('上传头像货物图片只能是 JPG ,PNG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isJPG && isLt2M;
		},
        closeWebsocket:function(){
			var _this=this;
            if(_this.socket){
                _this.socket.close();
                _this.socket=undefined;
            }
		},
        initWebsocket:function () {
            var _this = this;
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            }else{
                console.log("您的浏览器支持WebSocket");

                //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
                //等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
                // socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
                // _this.socket = new WebSocket("/websocket/1".replace("http","ws"));
                if(_this.socket){//如果socket开启，则不进行再次开启
                    return;
                }

                var localhostPaht= window.location.host
                _this.socket = new WebSocket("ws://"+localhostPaht+"/websocket/goods");
                //打开事件
                _this.socket.onopen = function() {
                    console.log("Socket 已打开");
                    alert("已经开始读取，请勿重复点击！！")
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };
                _this.epcMap=new Map();
                //获得消息事件
                _this.socket.onmessage = function(msg) {
                    console.log(msg.data);
                    if(msg.data!='连接成功，正在等待数据返回'){
						var data=JSON.parse(msg.data);
						if(data.epc=='-1'){
                            layer.open({
                                content: '该条码已被使用！！！'
                                ,skin: 'msg'
                                ,time: 2000 //2秒后自动关闭
                            });
                            return;
						}
						for (var i = 0; i < vm.bGoodsList.length; i++) {
							if(vm.bGoodsList[i].labelErp ==''||vm.bGoodsList[i].labelErp==undefined){
								vm.bGoodsList[i].labelErp=data.epc;
								vm.epcList.push(data.epc)
								return;
							}else if(vm.bGoodsList[i].labelErp==data.epc){
								return;
							}
						}
                    }else{
                    	alert("开始读取，请将物品上的标签放到读卡器上！！！")
					}

                  /*  $("#contentDiv").append("<p>"+msg.data+"</p>")
                    console.log(JSON.parse(msg.data));
                    var data = JSON.parse(msg.data);
                    if(msg.data!=null && msg.data!=undefined && data.wd!=null && data.sd!=undefined){
                        _this.wdOption.series[0].data=[{value: data.wd, name: '温度'}];
                        _this.myChart.setOption( _this.wdOption);
                        _this.sdOption.series[0].data=[{value: data.sd, name: '湿度'}];
                        _this.myChart1.setOption( _this.sdOption);
                    }*/


                    //发现消息进入    开始处理前端触发逻辑
                };
                //关闭事件
                _this.socket.onclose = function() {
                    console.log("Socket已关闭");
                };
                //发生了错误事件
                _this.socket.onerror = function() {
                    alert("Socket发生了错误");
                    //此时可以尝试刷新页面
                }
            }
        },
        readRFID:function () {
			/*var str='请将物品放到机器上！！';
			if(vm.epcList.length>=vm.bGoodsList.length){
				str='确定重新读取物品吗？'
			}*/
            //window.confirm(str, function(){
                vm.epcList=[]
               vm.initWebsocket();
            //});
        },
		//检测
        test:function () {
        	vm.bGoodsTest={
        		type:0,
                goodsName:'',
				ids:[]
			}
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            for (var i = 0; i < ids.length; i++) {
                var row=getRowData(ids[i]);
                if(row.goodsStatus!=3){
                    alert("您选择的物品存在不处于待检测状态下的，请去除后在进行该操作！！")
                    return;
                }
                if(i>0){
                    vm.bGoodsTest.goodsName+=",";
                }
                vm.bGoodsTest.goodsName+=row.goodsName;
                vm.bGoodsTest.ids.push(row.id);
            }
            vm.title = "检测";
            //vm.getInfo(id)
            vm.isTest=true;
        },
        saveTest:function () {
        	var that=this;
            $.ajax({
                type: "POST",
                url: baseURL + "goods/bgoodsrecord/savebGoodsRecord",
                contentType: "application/json",
                data: JSON.stringify(vm.bGoodsTest),
                success: function(r){
                    if(r.code == 0){
                        alert('操作成功', function(index){
                            that.isTest=false;
                            that.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        }


	}
});

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}